package com.yoyo.yyadsdk.util;

import com.anye.greendao.gen.AdvScreenEntityDao;
import com.anye.greendao.gen.DaoSession;
import com.anye.greendao.gen.LocalAdvEntityDao;
import com.yoyo.yyadsdk.bean.dao.AdvScreenEntity;
import com.yoyo.yyadsdk.bean.dao.LocalAdvEntity;
import com.yoyo.yyadsdk.bean.dao.RuleListEntity;
import com.yoyo.yyadsdk.config.PullFeature;

import java.util.ArrayList;
import java.util.List;

import static com.yoyo.yyadsdk.config.PullFeature.USE_STATUS_ENABLE;

class AdvType {
    private boolean myResult;
    private Integer[] mActionType;
    private List<AdvScreenEntity> mAdvScreenEntities;
    private List<LocalAdvEntity> mLocalAdvEntityList;
    private List<RuleListEntity> mRuleListEntityList;

    AdvType(Integer... actionType) {
        mActionType = actionType;
    }

    boolean is() {
        return myResult;
    }

    List<AdvScreenEntity> getAdvScreenEntities() {
        return mAdvScreenEntities;
    }

    List<LocalAdvEntity> getLocalAdvEntityList() {
        return mLocalAdvEntityList;
    }

    List<RuleListEntity> getRuleListEntityList() {
        return mRuleListEntityList;
    }

    AdvType invoke() {
        DaoSession daoSession = GreenDaoManager.getInstance().getDaoSession();
        //判断距上次展示间隔
        List<LocalAdvEntity> list = daoSession.getLocalAdvEntityDao().queryBuilder()
                .orderDesc(LocalAdvEntityDao.Properties.LastShowTime).limit(1).list();
        long lastTime = 0;
        if (list.size() > 0) {
            lastTime = list.get(0).getLastShowTime();
        }
        if (PullFeature.getAdFeatureInterval() > System.currentTimeMillis() - lastTime) {
            myResult = true;
            return this;
        }
        //获取对应类型的可用广告
        mAdvScreenEntities = daoSession.getAdvScreenEntityDao().queryBuilder()
                .where(AdvScreenEntityDao.Properties.Type.in((Object[]) mActionType),
                        AdvScreenEntityDao.Properties.Status.eq(USE_STATUS_ENABLE))
                .orderDesc(AdvScreenEntityDao.Properties.Priority).list();

        List<Integer> aIds = new ArrayList<>();
        for (AdvScreenEntity a : mAdvScreenEntities) {
            aIds.add(a.getId());
        }
        mLocalAdvEntityList = null;
        if (aIds.size() > 0) {
            mLocalAdvEntityList = daoSession.getLocalAdvEntityDao().queryBuilder()
                    .orderDesc(LocalAdvEntityDao.Properties.LastShowTime)
                    .where(LocalAdvEntityDao.Properties.AdvId.in(aIds),
                            LocalAdvEntityDao.Properties.FrequencyId.ge(SpUtil.getAdFrequencyId())).list();
        }
        mRuleListEntityList = daoSession.getRuleListEntityDao().queryBuilder().list();
        myResult = false;
        return this;
    }
}